package cloud.code.serverOne.web.config;

import cloud.code.baseProject.constant.Constant;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class GlobalExceptionHandler implements HandlerExceptionResolver {

    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        logger.error("全局异常拦截:", e);
        ModelAndView mv = new ModelAndView();
        httpServletResponse.setStatus(HttpStatus.OK.value()); //设置状态码
        httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE); //设置ContentType
        httpServletResponse.setCharacterEncoding("UTF-8"); //避免乱码
        httpServletResponse.setHeader("Cache-Control", "no-cache, must-revalidate");
        String resultJson = Constant.serviceError;
        if (e instanceof AuthorizationException) {
            resultJson = Constant.noAuth;
        } else if (e instanceof UnknownAccountException) {
            resultJson = Constant.noUser;
        } else if (e instanceof IncorrectCredentialsException) {
            resultJson = Constant.passwordError;
        }
        try {
            httpServletResponse.getWriter().write(resultJson);
        } catch (IOException e1) {
            logger.error("与客户端通讯异常:" + e1.getMessage(), e1);
        }
        return mv;
    }
}
